package org.javaboy.dynamic_datasource.ds;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@EnableAspectJAutoProxy
public class DsAspect {

    @Pointcut("@annotation(org.javaboy.dynamic_datasource.ds.Ds)")
    public void pc1() {

    }

    @Around("pc1()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        Ds ds = method.getAnnotation(Ds.class);
        //这是需要使用的数据源名称
        String value = ds.value();
        DynamicDataSourceContextHolder.setDataSource(value);
        //执行被拦截的方法
        Object proceed = pjp.proceed();
        DynamicDataSourceContextHolder.remove();
        return proceed;
    }
}
